﻿using UnityEngine;
using System.Collections.Generic;
using System;

public static class Utils
{
   public static void Forecah<TKey, TValue>(this Dictionary<TKey, TValue> dict,System.Action<TKey, TValue> EnumeratorFunc)
   {
       if (dict == null || EnumeratorFunc == null)
           throw new System.ArgumentNullException();
       var i = dict.GetEnumerator();
       while (i.MoveNext())
        {
            EnumeratorFunc(i.Current.Key, i.Current.Value);
        }
   }
 }

public class test:MonoBehaviour
{

    public Action<int, int> pCall;
    void Start()
    {
        pCall = CallVariable;
    }
    void FixedCall()
    {
        table.Forecah(pCall);//没有额外GC
        table.Forecah(CallVariable);//有104B GC
    }
    void CallVariable(int k, int v)
    {
        count = k + v;
    }



    Dictionary<int, int> table = new Dictionary<int, int>();
    public int count;
    //void Start()
    //{
    //    table.Add(1, 1);
    //    table.Add(2, 2);
    //    table.Add(3, 3);
    //    table.Add(4, 4);
    //    table.Add(5, 5);
    //    count = 0;
    //}
    void Update()
    {
        //Profiler.BeginSample("AnonymousWithoutParam");  // 未使用外部变量的匿名函数
        //AnonymousWithoutVariable();
        //Profiler.EndSample();
        //Profiler.BeginSample("FunctionWithoutVariable"); // 未使用外部变量的成员函数
        //FunctionWithoutVariable();
        //Profiler.EndSample();
        //Profiler.BeginSample("AnonymousParam"); // 使用外部变量的匿名函数
        //AnonymousVariable();
        //Profiler.EndSample();
        //Profiler.BeginSample("FunctionVariable"); // 使用外部变量的成员函数
        //FunctionVariable();
        //Profiler.EndSample();

        Profiler.BeginSample("FixedCall"); // 使用外部变量的成员函数
        FixedCall();
        Profiler.EndSample();
    }

    void AnonymousWithoutVariable()
     {
       table.Forecah((k, v) =>
       {
           int c = 0;
           c = k + v;
       });
     }

     void FunctionWithoutVariable()
     {
       table.Forecah(AddWithoutVariable);
     }
     void AddWithoutVariable(int k, int v)
     {
        int c = 0;
        c = k + v;
     }
    void AnonymousVariable()
    {
        table.Forecah((k, v) =>
        {
            count = k + v;
        });
    }

    void FunctionVariable()
    {
        table.Forecah(AddtVariable);
    }   
    void AddtVariable(int k, int v)
    {
        count = k + v;
    }

}